﻿using System.Collections.Generic;
using System.Web.Http;
using WebApiThrottle;
using XieCan.AspMVC.JWTAuth;
using XieCan.AspMVC.Mapper;
using XieCan.AspMVC.Models;
using XieCan.AspMVC.ViewModels;

namespace XieCan.AspMVC.WebApi.Controllers
{
    /// <summary>
    /// 账号管理
    /// </summary>
    public class AccountController : BaseController
    {
        /// <summary>
        /// 账户注册
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpPost]
        public OperateResult<bool> Register([FromBody] SimpleLoginViewModel login)
        {
            if (login != null)
            {
                var account = login.MapTo<AccountModel>();
                return AccountService.Register(account);
            }
            return OperateResult<bool>.Failed("请输入账号和密码");
        }

        /// <summary>
        /// 账户登录
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpPost]
        [DisableThrotting]//不限流
        public OperateResult<string> Login([FromBody] SimpleLoginViewModel login)
        {
            if (login != null)
            {
                var result = AccountService.Login(login.MapTo<AccountModel>());
                if (result.Success)
                {
                    var model = result.Data.MapTo<LoginResultViewModel>();
                    try
                    {
                        var claims = new Dictionary<string, object>
                        {
                            { "Account", model.Account},
                            { "Role", model.Role?.Name??"未指定角色"}
                        };
                        return JWTHelper.Encoder(claims);
                    }
                    catch (System.Exception ex)
                    {
                        return OperateResult<string>.Failed(ex);
                    }
                }
                return OperateResult<string>.Failed(result.Message);
            }
            return OperateResult<string>.Failed("请输入账号和密码");
        }
    }
}